merged from master
[lhc/web/wiklou.git] / includes / api / ApiEditPage.php
1 <?php
2 /**
3 *
4 *
5 * Created on August 16, 2007
6 *
7 * Copyright © 2007 Iker Labarga <Firstname><Lastname>@gmail.com
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26
27 /**
28 * A module that allows for editing and creating pages.
29 *
30 * Currently, this wraps around the EditPage class in an ugly way,
31 * EditPage.php should be rewritten to provide a cleaner interface
32 * @ingroup API
33 */
34 class ApiEditPage extends ApiBase {
35
36 public function __construct( $query, $moduleName ) {
37 parent::__construct( $query, $moduleName );
38 }
39
40 public function execute() {
41 $user = $this->getUser();
42 $params = $this->extractRequestParams();
43
44 if ( is_null( $params['text'] ) && is_null( $params['appendtext'] ) &&
45 is_null( $params['prependtext'] ) &&
46 $params['undo'] == 0 )
47 {
48 $this->dieUsageMsg( 'missingtext' );
49 }
50
51 $titleObj = $this->getTitleOrPageId( $params );
52 if ( $titleObj->isExternal() ) {
53 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
54 }
55
56 $apiResult = $this->getResult();
57
58 if ( $params['redirect'] ) {
59 if ( $titleObj->isRedirect() ) {
60 $oldTitle = $titleObj;
61
62 $titles = Title::newFromRedirectArray( Revision::newFromTitle( $oldTitle )->getText( Revision::FOR_THIS_USER ) );
63 // array_shift( $titles );
64
65 $redirValues = array();
66 foreach ( $titles as $id => $newTitle ) {
67
68 if ( !isset( $titles[ $id - 1 ] ) ) {
69 $titles[ $id - 1 ] = $oldTitle;
70 }
71
72 $redirValues[] = array(
73 'from' => $titles[ $id - 1 ]->getPrefixedText(),
74 'to' => $newTitle->getPrefixedText()
75 );
76
77 $titleObj = $newTitle;
78 }
79
80 $apiResult->setIndexedTagName( $redirValues, 'r' );
81 $apiResult->addValue( null, 'redirects', $redirValues );
82 }
83 }
84
85 if ( $params['createonly'] && $titleObj->exists() ) {
86 $this->dieUsageMsg( 'createonly-exists' );
87 }
88 if ( $params['nocreate'] && !$titleObj->exists() ) {
89 $this->dieUsageMsg( 'nocreate-missing' );
90 }
91
92 // Now let's check whether we're even allowed to do this
93 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
94 if ( !$titleObj->exists() ) {
95 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
96 }
97 if ( count( $errors ) ) {
98 $this->dieUsageMsg( $errors[0] );
99 }
100
101 $articleObj = Article::newFromTitle( $titleObj, $this->getContext() );
102
103 $toMD5 = $params['text'];
104 if ( !is_null( $params['appendtext'] ) || !is_null( $params['prependtext'] ) )
105 {
106 // For non-existent pages, Article::getContent()
107 // returns an interface message rather than ''
108 // We do want getContent()'s behavior for non-existent
109 // MediaWiki: pages, though
110 if ( $articleObj->getID() == 0 && $titleObj->getNamespace() != NS_MEDIAWIKI ) {
111 $content = null;
112 $text = '';
113 } else {
114 $content = $articleObj->getContentObject();
115 $text = ContentHandler::getContentText( $content ); #FIXME: serialize?! get format from params?...
116 }
117
118 if ( !is_null( $params['section'] ) ) {
119 // Process the content for section edits
120 $section = intval( $params['section'] );
121 $sectionContent = $content->getSection( $section );
122 $text = ContentHandler::getContentText( $sectionContent ); #FIXME: serialize?! get format from params?...
123 if ( $text === false || $text === null ) {
124 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
125 }
126 }
127 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
128 $toMD5 = $params['prependtext'] . $params['appendtext'];
129 }
130
131 if ( $params['undo'] > 0 ) {
132 if ( $params['undoafter'] > 0 ) {
133 if ( $params['undo'] < $params['undoafter'] ) {
134 list( $params['undo'], $params['undoafter'] ) =
135 array( $params['undoafter'], $params['undo'] );
136 }
137 $undoafterRev = Revision::newFromID( $params['undoafter'] );
138 }
139 $undoRev = Revision::newFromID( $params['undo'] );
140 if ( is_null( $undoRev ) || $undoRev->isDeleted( Revision::DELETED_TEXT ) ) {
141 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
142 }
143
144 if ( $params['undoafter'] == 0 ) {
145 $undoafterRev = $undoRev->getPrevious();
146 }
147 if ( is_null( $undoafterRev ) || $undoafterRev->isDeleted( Revision::DELETED_TEXT ) ) {
148 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
149 }
150
151 if ( $undoRev->getPage() != $articleObj->getID() ) {
152 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
153 }
154 if ( $undoafterRev->getPage() != $articleObj->getID() ) {
155 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
156 }
157
158 $newtext = $articleObj->getUndoText( $undoRev, $undoafterRev );
159 if ( $newtext === false ) {
160 $this->dieUsageMsg( 'undo-failure' );
161 }
162 $params['text'] = $newtext;
163 // If no summary was given and we only undid one rev,
164 // use an autosummary
165 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
166 $params['summary'] = wfMsgForContent( 'undo-summary', $params['undo'], $undoRev->getUserText() );
167 }
168 }
169
170 // See if the MD5 hash checks out
171 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
172 $this->dieUsageMsg( 'hashcheckfailed' );
173 }
174
175 // EditPage wants to parse its stuff from a WebRequest
176 // That interface kind of sucks, but it's workable
177 $requestArray = array(
178 'wpTextbox1' => $params['text'],
179 'wpEditToken' => $params['token'],
180 'wpIgnoreBlankSummary' => ''
181 );
182
183 if ( !is_null( $params['summary'] ) ) {
184 $requestArray['wpSummary'] = $params['summary'];
185 }
186
187 if ( !is_null( $params['sectiontitle'] ) ) {
188 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
189 }
190
191 // Watch out for basetimestamp == ''
192 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
193 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
194 $requestArray['wpEdittime'] = wfTimestamp( TS_MW, $params['basetimestamp'] );
195 } else {
196 $requestArray['wpEdittime'] = $articleObj->getTimestamp();
197 }
198
199 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
200 $requestArray['wpStarttime'] = wfTimestamp( TS_MW, $params['starttimestamp'] );
201 } else {
202 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
203 }
204
205 if ( $params['minor'] || ( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
206 $requestArray['wpMinoredit'] = '';
207 }
208
209 if ( $params['recreate'] ) {
210 $requestArray['wpRecreate'] = '';
211 }
212
213 if ( !is_null( $params['section'] ) ) {
214 $section = intval( $params['section'] );
215 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
216 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
217 }
218 $requestArray['wpSection'] = $params['section'];
219 } else {
220 $requestArray['wpSection'] = '';
221 }
222
223 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
224
225 // Deprecated parameters
226 if ( $params['watch'] ) {
227 $watch = true;
228 } elseif ( $params['unwatch'] ) {
229 $watch = false;
230 }
231
232 if ( $watch ) {
233 $requestArray['wpWatchthis'] = '';
234 }
235
236 global $wgTitle, $wgRequest;
237
238 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
239
240 // Some functions depend on $wgTitle == $ep->mTitle
241 // TODO: Make them not or check if they still do
242 $wgTitle = $titleObj;
243
244 $handler = ContentHandler::getForTitle( $titleObj );
245 $ep = $handler->createEditPage( $articleObj );
246
247 $ep->setContextTitle( $titleObj );
248 $ep->importFormData( $req );
249
250 // Run hooks
251 // Handle APIEditBeforeSave parameters
252 $r = array();
253 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1, &$r ) ) ) {
254 if ( count( $r ) ) {
255 $r['result'] = 'Failure';
256 $apiResult->addValue( null, $this->getModuleName(), $r );
257 return;
258 } else {
259 $this->dieUsageMsg( 'hookaborted' );
260 }
261 }
262
263 // Do the actual save
264 $oldRevId = $articleObj->getRevIdFetched();
265 $result = null;
266 // Fake $wgRequest for some hooks inside EditPage
267 // @todo FIXME: This interface SUCKS
268 $oldRequest = $wgRequest;
269 $wgRequest = $req;
270
271 $status = $ep->internalAttemptSave( $result, $user->isAllowed( 'bot' ) && $params['bot'] );
272 $wgRequest = $oldRequest;
273 global $wgMaxArticleSize;
274
275 switch( $status->value ) {
276 case EditPage::AS_HOOK_ERROR:
277 case EditPage::AS_HOOK_ERROR_EXPECTED:
278 $this->dieUsageMsg( 'hookaborted' );
279
280 case EditPage::AS_IMAGE_REDIRECT_ANON:
281 $this->dieUsageMsg( 'noimageredirect-anon' );
282
283 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
284 $this->dieUsageMsg( 'noimageredirect-logged' );
285
286 case EditPage::AS_SPAM_ERROR:
287 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
288
289 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
290 $this->dieUsageMsg( 'blockedtext' );
291
292 case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
293 case EditPage::AS_CONTENT_TOO_BIG:
294 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
295
296 case EditPage::AS_READ_ONLY_PAGE_ANON:
297 $this->dieUsageMsg( 'noedit-anon' );
298
299 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
300 $this->dieUsageMsg( 'noedit' );
301
302 case EditPage::AS_READ_ONLY_PAGE:
303 $this->dieReadOnly();
304
305 case EditPage::AS_RATE_LIMITED:
306 $this->dieUsageMsg( 'actionthrottledtext' );
307
308 case EditPage::AS_ARTICLE_WAS_DELETED:
309 $this->dieUsageMsg( 'wasdeleted' );
310
311 case EditPage::AS_NO_CREATE_PERMISSION:
312 $this->dieUsageMsg( 'nocreate-loggedin' );
313
314 case EditPage::AS_BLANK_ARTICLE:
315 $this->dieUsageMsg( 'blankpage' );
316
317 case EditPage::AS_CONFLICT_DETECTED:
318 $this->dieUsageMsg( 'editconflict' );
319
320 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
321 case EditPage::AS_TEXTBOX_EMPTY:
322 $this->dieUsageMsg( 'emptynewsection' );
323
324 case EditPage::AS_SUCCESS_NEW_ARTICLE:
325 $r['new'] = '';
326
327 case EditPage::AS_SUCCESS_UPDATE:
328 $r['result'] = 'Success';
329 $r['pageid'] = intval( $titleObj->getArticleID() );
330 $r['title'] = $titleObj->getPrefixedText();
331 $newRevId = $articleObj->getLatest();
332 if ( $newRevId == $oldRevId ) {
333 $r['nochange'] = '';
334 } else {
335 $r['oldrevid'] = intval( $oldRevId );
336 $r['newrevid'] = intval( $newRevId );
337 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601,
338 $articleObj->getTimestamp() );
339 }
340 break;
341
342 case EditPage::AS_SUMMARY_NEEDED:
343 $this->dieUsageMsg( 'summaryrequired' );
344
345 case EditPage::AS_END:
346 // $status came from WikiPage::doEdit()
347 $errors = $status->getErrorsArray();
348 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
349 break;
350 default:
351 if ( is_string( $status->value ) && strlen( $status->value ) ) {
352 $this->dieUsage( "An unknown return value was returned by Editpage. The code returned was \"{$status->value}\"" , $status->value );
353 } else {
354 $this->dieUsageMsg( array( 'unknownerror', $status->value ) );
355 }
356 }
357 $apiResult->addValue( null, $this->getModuleName(), $r );
358 }
359
360 public function mustBePosted() {
361 return true;
362 }
363
364 public function isWriteMode() {
365 return true;
366 }
367
368 public function getDescription() {
369 return 'Create and edit pages.';
370 }
371
372 public function getPossibleErrors() {
373 global $wgMaxArticleSize;
374
375 return array_merge( parent::getPossibleErrors(),
376 $this->getTitleOrPageIdErrorMessage(),
377 array(
378 array( 'nosuchpageid', 'pageid' ),
379 array( 'missingtext' ),
380 array( 'invalidtitle', 'title' ),
381 array( 'createonly-exists' ),
382 array( 'nocreate-missing' ),
383 array( 'nosuchrevid', 'undo' ),
384 array( 'nosuchrevid', 'undoafter' ),
385 array( 'revwrongpage', 'id', 'text' ),
386 array( 'undo-failure' ),
387 array( 'hashcheckfailed' ),
388 array( 'hookaborted' ),
389 array( 'noimageredirect-anon' ),
390 array( 'noimageredirect-logged' ),
391 array( 'spamdetected', 'spam' ),
392 array( 'summaryrequired' ),
393 array( 'blockedtext' ),
394 array( 'contenttoobig', $wgMaxArticleSize ),
395 array( 'noedit-anon' ),
396 array( 'noedit' ),
397 array( 'actionthrottledtext' ),
398 array( 'wasdeleted' ),
399 array( 'nocreate-loggedin' ),
400 array( 'blankpage' ),
401 array( 'editconflict' ),
402 array( 'emptynewsection' ),
403 array( 'unknownerror', 'retval' ),
404 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
405 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
406 array( 'customcssprotected' ),
407 array( 'customjsprotected' ),
408 )
409 );
410 }
411
412 public function getAllowedParams() {
413 return array(
414 'title' => array(
415 ApiBase::PARAM_TYPE => 'string',
416 ),
417 'pageid' => array(
418 ApiBase::PARAM_TYPE => 'integer',
419 ),
420 'section' => null,
421 'sectiontitle' => array(
422 ApiBase::PARAM_TYPE => 'string',
423 ApiBase::PARAM_REQUIRED => false,
424 ),
425 'text' => null,
426 'token' => null,
427 'summary' => null,
428 'minor' => false,
429 'notminor' => false,
430 'bot' => false,
431 'basetimestamp' => null,
432 'starttimestamp' => null,
433 'recreate' => false,
434 'createonly' => false,
435 'nocreate' => false,
436 'watch' => array(
437 ApiBase::PARAM_DFLT => false,
438 ApiBase::PARAM_DEPRECATED => true,
439 ),
440 'unwatch' => array(
441 ApiBase::PARAM_DFLT => false,
442 ApiBase::PARAM_DEPRECATED => true,
443 ),
444 'watchlist' => array(
445 ApiBase::PARAM_DFLT => 'preferences',
446 ApiBase::PARAM_TYPE => array(
447 'watch',
448 'unwatch',
449 'preferences',
450 'nochange'
451 ),
452 ),
453 'md5' => null,
454 'prependtext' => null,
455 'appendtext' => null,
456 'undo' => array(
457 ApiBase::PARAM_TYPE => 'integer'
458 ),
459 'undoafter' => array(
460 ApiBase::PARAM_TYPE => 'integer'
461 ),
462 'redirect' => array(
463 ApiBase::PARAM_TYPE => 'boolean',
464 ApiBase::PARAM_DFLT => false,
465 ),
466 );
467 }
468
469 public function getParamDescription() {
470 $p = $this->getModulePrefix();
471 return array(
472 'title' => "Title of the page you want to edit. Cannot be used together with {$p}pageid",
473 'pageid' => "Page ID of the page you want to edit. Cannot be used together with {$p}title",
474 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
475 'sectiontitle' => 'The title for a new section',
476 'text' => 'Page content',
477 'token' => array( 'Edit token. You can get one of these through prop=info.',
478 "The token should always be sent as the last parameter, or at least, after the {$p}text parameter"
479 ),
480 'summary' => "Edit summary. Also section title when {$p}section=new and {$p}sectiontitle is not set",
481 'minor' => 'Minor edit',
482 'notminor' => 'Non-minor edit',
483 'bot' => 'Mark this edit as bot',
484 'basetimestamp' => array( 'Timestamp of the base revision (obtained through prop=revisions&rvprop=timestamp).',
485 'Used to detect edit conflicts; leave unset to ignore conflicts'
486 ),
487 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
488 'Used to detect edit conflicts; leave unset to ignore conflicts'
489 ),
490 'recreate' => 'Override any errors about the article having been deleted in the meantime',
491 'createonly' => 'Don\'t edit the page if it exists already',
492 'nocreate' => 'Throw an error if the page doesn\'t exist',
493 'watch' => 'Add the page to your watchlist',
494 'unwatch' => 'Remove the page from your watchlist',
495 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
496 'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
497 'If set, the edit won\'t be done unless the hash is correct' ),
498 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
499 'appendtext' => array( "Add this text to the end of the page. Overrides {$p}text.",
500 "Use {$p}section=new to append a new section" ),
501 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
502 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
503 'redirect' => 'Automatically resolve redirects',
504 );
505 }
506
507 public function needsToken() {
508 return true;
509 }
510
511 public function getTokenSalt() {
512 return '';
513 }
514
515 public function getExamples() {
516 return array(
517
518 'api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\'
519 => 'Edit a page (anonymous user)',
520
521 'api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\'
522 => 'Prepend __NOTOC__ to a page (anonymous user)',
523 'api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\'
524 => 'Undo r13579 through r13585 with autosummary (anonymous user)',
525 );
526 }
527
528 public function getHelpUrls() {
529 return 'https://www.mediawiki.org/wiki/API:Edit';
530 }
531
532 public function getVersion() {
533 return __CLASS__ . ': $Id$';
534 }
535 }